package com.atguigu.lease.web.admin.service.imp;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.ThreadLocalLoginUserContext;
import com.atguigu.lease.common.exception.LoginException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import io.jsonwebtoken.Claims;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    SystemUserService systemUserService;


    @Override
    public CaptchaVo getCaptcha() {

        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String image = specCaptcha.toBase64();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+UUID.randomUUID().toString().replace("-", "");


        String text = specCaptcha.text().toLowerCase();
        //将用户的key 和value 过期时间储存到redis 60秒过期
        redisTemplate.opsForValue().set(key, text, RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);


        return new CaptchaVo(image, key);
    }

    @Override
    public String login(LoginVo loginVo) {

        //验证图片验证码
        String captchaKey = loginVo.getCaptchaKey();
        String userCode = loginVo.getCaptchaCode().toLowerCase();

        String CacheCode = redisTemplate.opsForValue().get(captchaKey);

        if (!userCode.equals(CacheCode)){
            //验证码错误
            throw new LoginException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //验证账号
        String username = loginVo.getUsername();

        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper =new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, username);

        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        if (systemUser==null){
            throw new LoginException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        String DBPassword = systemUser.getPassword();

        // 验证密码
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!DBPassword.equals(password)){
            throw  new LoginException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 用户被禁用
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw  new LoginException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //确认用户账号密码 并且没被禁用后删除redis的验证码
        redisTemplate.delete(captchaKey);

        return JwtUtil.createToken(systemUser.getId(), systemUser.getName());
    }

    @Override
    public SystemUserInfoVo selectSystemUserInfo() {

        LoginUser loginUser = ThreadLocalLoginUserContext.getLoginUser();

        SystemUser systemUser = systemUserService.getById(loginUser.getUserId());

        SystemUserInfoVo systemUserInfoVo =new SystemUserInfoVo();
        BeanUtils.copyProperties(systemUser,systemUserInfoVo);
        return systemUserInfoVo;
    }
}
